// 玩家类
class Player {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.radius = 16;
        this.health = 100;
        this.maxHealth = 100;
        this.speed = 200; // 像素/秒
        
        console.log('玩家创建在位置:', x, y);
        
        // 武器系统
        this.currentWeapon = new Weapon('pistol', 30, 90, 500, 10);
        this.weapons = [this.currentWeapon];
        
        // 近战武器系统
        this.meleeWeapon = new MeleeWeapon('knife');
        this.meleeWeapons = [this.meleeWeapon];
        
        // 战斗模式系统
        this.combatMode = 'ranged'; // 'ranged' 或 'melee'
        this.lastModeSwitch = 0;
        this.modeSwitchCooldown = 500; // 500ms切换冷却
        
        // 近战攻击系统
        this.isAttacking = false;
        this.attackStartTime = 0;
        this.attackDuration = 300; // 攻击动画持续时间
        this.lastMeleeAttack = 0;
        this.meleeCombo = 0; // 连击数
        this.maxCombo = 3;
        this.comboResetTime = 1000; // 1秒后重置连击
        
        // 动画系统
        this.facing = 0; // 面向角度
        this.animationFrame = 0;
        this.animationTime = 0;
        this.isMoving = false;
        
        // 颜色 (像素艺术风格)
        this.colors = {
            body: '#8B4513',
            clothes: '#4169E1',
            hair: '#654321',
            weapon: '#696969'
        };
        
        // 道具效果
        this.activeEffects = {};
        this.shield = 0;
        this.explosiveAmmo = 0;
        
        // 战斗状态追踪
        this.lastDamageTime = 0; // 上次受到伤害的时间
    }
    
    update(deltaTime, keys, mouse) {
        this.handleMovement(deltaTime, keys);
        this.handleRotation(mouse);
        this.updateAnimation(deltaTime);
        this.updateWeapon(deltaTime);
        this.updateCombatSystem(deltaTime, keys, mouse);
        
        // 处理模式切换 (Q键)
        if (keys['KeyQ'] && Date.now() - this.lastModeSwitch > this.modeSwitchCooldown) {
            this.switchCombatMode();
        }
        
        // 处理持续攻击输入（连发武器）
        if (mouse.down && this.combatMode === 'ranged') {
            // 远程自动射击 (如果武器允许连发)
            if (this.currentWeapon && (this.currentWeapon.type === 'smg' || this.currentWeapon.type === 'rifle' || this.currentWeapon.type === 'minigun')) {
                this.shoot(mouse.x, mouse.y);
            }
        }
        
        // 处理快速换弹 (空格键)
        if (keys['Space'] && this.combatMode === 'ranged') {
            this.quickReload();
        }
    }
    
    handleMovement(deltaTime, keys) {
        let dx = 0;
        let dy = 0;
        
        if (keys['KeyW'] || keys['ArrowUp']) dy -= 1;
        if (keys['KeyS'] || keys['ArrowDown']) dy += 1;
        if (keys['KeyA'] || keys['ArrowLeft']) dx -= 1;
        if (keys['KeyD'] || keys['ArrowRight']) dx += 1;
        
        // 归一化对角移动
        if (dx !== 0 && dy !== 0) {
            dx *= 0.707;
            dy *= 0.707;
        }
        
        this.isMoving = (dx !== 0 || dy !== 0);
        
        if (this.isMoving) {
            this.x += dx * this.speed * deltaTime / 1000;
            this.y += dy * this.speed * deltaTime / 1000;
            
            // 边界检查
            const canvas = document.getElementById('gameCanvas');
            this.x = Math.max(this.radius, Math.min(canvas.width - this.radius, this.x));
            this.y = Math.max(this.radius, Math.min(canvas.height - this.radius, this.y));
        }
    }
    
    handleRotation(mouse) {
        const canvas = document.getElementById('gameCanvas');
        const rect = canvas.getBoundingClientRect();
        
        // 计算面向角度
        const dx = mouse.x - this.x;
        const dy = mouse.y - this.y;
        this.facing = Math.atan2(dy, dx);
    }
    
    updateAnimation(deltaTime) {
        if (this.isMoving) {
            this.animationTime += deltaTime;
            if (this.animationTime > 200) {
                this.animationFrame = (this.animationFrame + 1) % 4;
                this.animationTime = 0;
            }
        } else {
            this.animationFrame = 0;
        }
    }
    
    updateWeapon(deltaTime) {
        if (this.currentWeapon) {
            this.currentWeapon.update(deltaTime);
        }
    }
    
    shoot(targetX, targetY) {
        if (!this.currentWeapon || !this.currentWeapon.canShoot()) {
            return;
        }
        
        const result = this.currentWeapon.shoot(this.x, this.y, targetX, targetY);
        if (result && window.gameEngine) {
            // 处理单发子弹（包括普通子弹、激光束、等离子球）
            if (result.constructor.name === 'Bullet' || 
                result.constructor.name === 'LaserBeam' || 
                result.constructor.name === 'PlasmaBolt') {
                window.gameEngine.bullets.push(result);
            }
            // 处理散弹枪多发子弹
            else if (Array.isArray(result)) {
                result.forEach(bullet => {
                    window.gameEngine.bullets.push(bullet);
                });
            }
            
            // 触发武器射击视觉效果
            if (window.visualEffects) {
                const angle = Math.atan2(targetY - this.y, targetX - this.x);
                const event = new CustomEvent('weaponFired', {
                    detail: {
                        x: this.x,
                        y: this.y,
                        angle: angle
                    }
                });
                document.dispatchEvent(event);
            }
            
            // 更新UI
            this.updateWeaponUI();
        }
    }
    
    reload() {
        if (this.currentWeapon) {
            this.currentWeapon.reload();
            this.updateWeaponUI();
            
            // 重装弹药时的视觉反馈
            if (window.gameEngine) {
                for (let i = 0; i < 3; i++) {
                    window.gameEngine.particles.push(new Particle(
                        this.x + (Math.random() - 0.5) * 20,
                        this.y + (Math.random() - 0.5) * 20,
                        (Math.random() - 0.5) * 30,
                        -Math.random() * 30,
                        '#FFD700',
                        300
                    ));
                }
            }
        }
    }
    
    // 快速换弹系统 - 1秒完成，只要有子弹就能换弹
    quickReload() {
        if (!this.currentWeapon || this.currentWeapon.isReloading) {
            return;
        }
        
        // 只要有备用弹药就可以换弹，不需要等到弹夹空
        if (this.currentWeapon.totalAmmo > 0) {
            this.currentWeapon.startQuickReload();
            this.updateWeaponUI();
            
            // 快速换弹的特殊视觉效果
            if (window.gameEngine) {
                for (let i = 0; i < 5; i++) {
                    window.gameEngine.particles.push(new Particle(
                        this.x + (Math.random() - 0.5) * 30,
                        this.y + (Math.random() - 0.5) * 30,
                        (Math.random() - 0.5) * 50,
                        -Math.random() * 50,
                        '#00FF00',
                        500
                    ));
                }
            }
            
        }
    }
    
    // 切换战斗模式
    switchCombatMode() {
        this.combatMode = this.combatMode === 'ranged' ? 'melee' : 'ranged';
        this.lastModeSwitch = Date.now();
        
        // 重置攻击状态
        this.isAttacking = false;
        this.meleeCombo = 0;
        
        // 显示模式切换提示
        this.showModeSwitch();
        this.updateWeaponUI();
        
        console.log('切换到', this.combatMode === 'ranged' ? '远程模式' : '近战模式');
    }
    
    // 更新战斗系统
    updateCombatSystem(deltaTime, keys, mouse) {
        // 更新近战武器
        if (this.meleeWeapon) {
            this.meleeWeapon.update(deltaTime);
        }
        
        // 更新攻击状态
        if (this.isAttacking) {
            if (Date.now() - this.attackStartTime > this.attackDuration) {
                this.isAttacking = false;
            }
        }
        
        // 重置连击计数器
        if (Date.now() - this.lastMeleeAttack > this.comboResetTime) {
            this.meleeCombo = 0;
        }
    }
    
    // 近战攻击
    performMeleeAttack(targetX, targetY) {
        if (!this.meleeWeapon || this.isAttacking) {
            return;
        }
        
        const currentTime = Date.now();
        if (currentTime - this.lastMeleeAttack < this.meleeWeapon.attackSpeed) {
            return;
        }
        
        // 开始攻击动画
        this.isAttacking = true;
        this.attackStartTime = currentTime;
        this.lastMeleeAttack = currentTime;
        
        // 更新连击
        this.meleeCombo = Math.min(this.meleeCombo + 1, this.maxCombo);
        
        // 执行近战攻击
        const result = this.meleeWeapon.attack(this.x, this.y, targetX, targetY, this.meleeCombo);
        
        if (result && window.gameEngine) {
            console.log(`近战攻击：${this.meleeWeapon.stats.name}, 伤害: ${result.damage}, 范围: ${result.range}`);
            
            // 处理攻击范围内的敌人
            this.processMeleeAttack(result);
            
            // 创建攻击特效
            this.createMeleeEffect(targetX, targetY);
        }
        
        // 更新UI
        this.updateWeaponUI();
    }
    
    // 处理近战攻击命中 - 使用和远程攻击完全相同的伤害逻辑
    processMeleeAttack(attackData) {
        const { range, damage, angle } = attackData;
        
        // 检查攻击范围内的敌人 - 使用和远程攻击相同的遍历方式
        if (window.gameEngine && window.gameEngine.zombies) {
            // 从后往前遍历，避免在遍历过程中移除元素导致的问题
            for (let zombieIndex = window.gameEngine.zombies.length - 1; zombieIndex >= 0; zombieIndex--) {
                const zombie = window.gameEngine.zombies[zombieIndex];
                
                const dx = zombie.x - this.x;
                const dy = zombie.y - this.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                if (distance <= range) {
                    // 检查角度（扇形攻击）
                    const zombieAngle = Math.atan2(dy, dx);
                    let angleDiff = Math.abs(zombieAngle - angle);
                    if (angleDiff > Math.PI) angleDiff = 2 * Math.PI - angleDiff;
                    
                    // 90度攻击范围
                    if (angleDiff <= Math.PI / 4) {
                        // 创建血溅效果 - 和远程攻击相同
                        if (window.gameEngine && typeof window.gameEngine.createBloodSplash === 'function') {
                            window.gameEngine.createBloodSplash(zombie.x, zombie.y);
                        }
                        
                        // 直接减少僵尸血量，避免zombie.takeDamage()的重复奖励问题
                        zombie.health -= damage;
                        zombie.addBloodStain && zombie.addBloodStain();
                        
                        // 击退效果
                        zombie.x += Math.cos(zombieAngle) * 20;
                        zombie.y += Math.sin(zombieAngle) * 20;
                        
                        // 记录近战击中统计
                        if (window.storageManager) {
                            window.storageManager.updateStatistics('meleeHit');
                        }
                        
                        // 如果僵尸死亡，移除它 - 和远程攻击完全相同的逻辑
                        if (zombie.health <= 0) {
                            window.gameEngine.zombies.splice(zombieIndex, 1);
                            
                            // 创建死亡特效
                            if (zombie.createDeathEffect) {
                                zombie.createDeathEffect();
                            }
                            
                            // 增加分数和统计 - 和远程攻击相同
                            if (window.gameManager) {
                                const comboBonus = this.meleeCombo * 5; // 连击奖励
                                window.gameManager.addScore(10 + comboBonus);
                            }
                            
                            if (window.storageManager) {
                                window.storageManager.updateStatistics('zombieKilled', 1, zombie.type);
                            }
                            
                            // 添加货币奖励 - 和远程攻击相同
                            if (window.roguelikeSystem && window.gameEngine && typeof window.gameEngine.calculateCoinReward === 'function') {
                                const coinReward = window.gameEngine.calculateCoinReward(zombie.type);
                                window.roguelikeSystem.addCurrency(coinReward);
                            } else if (window.roguelikeSystem) {
                                // 默认货币奖励
                                const defaultReward = zombie.type === 'tank' ? 5 : zombie.type === 'fast' ? 3 : 2;
                                window.roguelikeSystem.addCurrency(defaultReward);
                            }
                            
                            // 添加经验值奖励 - 和远程攻击相同
                            if (window.weaponEnhancement && window.gameEngine && typeof window.gameEngine.calculateExpReward === 'function') {
                                const expReward = window.gameEngine.calculateExpReward(zombie.type);
                                window.weaponEnhancement.addExperience(expReward);
                            } else if (window.weaponEnhancement) {
                                // 默认经验奖励
                                const defaultExp = zombie.expReward || (zombie.type === 'tank' ? 15 : zombie.type === 'fast' ? 8 : 10);
                                window.weaponEnhancement.addExperience(defaultExp);
                                
                                // 技能点奖励
                                if (zombie.skillPoints && zombie.skillPoints > 0) {
                                    window.weaponEnhancement.skillPoints += zombie.skillPoints;
                                }
                            }
                            
                            console.log(`近战击杀：${zombie.type}僵尸，获得奖励`);
                        } else {
                            // 僵尸未死亡时的分数奖励
                            if (window.gameManager) {
                                const comboBonus = this.meleeCombo * 2;
                                window.gameManager.addScore(5 + comboBonus);
                            }
                        }
                        
                        console.log(`近战武器击中！伤害: ${damage}, 僵尸剩余血量: ${zombie.health}`);
                    }
                }
            }
        }
        
        // 检查BOSS
        if (window.gameEngine && window.gameEngine.boss) {
            const boss = window.gameEngine.boss;
            const dx = boss.x - this.x;
            const dy = boss.y - this.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            if (distance <= range) {
                const bossAngle = Math.atan2(dy, dx);
                let angleDiff = Math.abs(bossAngle - angle);
                if (angleDiff > Math.PI) angleDiff = 2 * Math.PI - angleDiff;
                
                if (angleDiff <= Math.PI / 4) {
                    if (typeof boss.takeDamage === 'function') {
                        boss.takeDamage(damage);
                        
                        // BOSS击中特效
                        this.createBossHitEffect(boss.x, boss.y);
                        
                        // BOSS击中奖励分数
                        if (window.gameManager) {
                            const comboBonus = this.meleeCombo * 10;
                            window.gameManager.addScore(25 + comboBonus);
                        }
                    }
                }
            }
        }
    }
    
    takeDamage(damage) {
        if (this.shield > 0) {
            this.shield--;
            // 护盾抵挡伤害的视觉效果
            this.createShieldEffect();
            
            // 记录护盾使用统计
            if (window.storageManager) {
                window.storageManager.updateStatistics('shieldTimeUsed', 1000); // 假设每次使用1秒
            }
            
            // 护盾抵挡时不扣分
            return;
        }
        
        this.health -= damage;
        this.health = Math.max(0, this.health);
        
        // 受伤扣分 - 根据伤害值扣分
        const scorePenalty = damage * 2; // 受到20伤害扣40分
        if (window.gameManager) {
            window.gameManager.subtractScore(scorePenalty);
        }
        
        // 记录受伤统计
        if (window.storageManager) {
            window.storageManager.updateStatistics('damageTaken', damage);
        }
        
        // 显示扣分提示
        this.showDamageScore(scorePenalty);
        
        // 更新UI
        this.updateHealthUI();
        
        // 受伤效果
        this.flashRed();
        
        if (this.health <= 0) {
            this.die();
        }
    }
    
    showDamageScore(penalty) {
        if (window.gameEngine) {
            window.gameEngine.floatingTexts = window.gameEngine.floatingTexts || [];
            window.gameEngine.floatingTexts.push(new FloatingText(
                this.x, this.y - 30, `-${penalty}分`, '#FF0000', 2000
            ));
        }
    }
    
    createShieldEffect() {
        if (window.gameEngine) {
            for (let i = 0; i < 8; i++) {
                const angle = (Math.PI * 2 / 8) * i;
                window.gameEngine.particles.push(new Particle(
                    this.x + Math.cos(angle) * 25,
                    this.y + Math.sin(angle) * 25,
                    Math.cos(angle) * 50,
                    Math.sin(angle) * 50,
                    '#4169E1',
                    800
                ));
            }
        }
    }
    
    heal(amount) {
        this.health += amount;
        this.health = Math.min(this.maxHealth, this.health);
        this.updateHealthUI();
    }
    
    // 受到伤害方法
    takeDamage(amount) {
        if (this.shield > 0) {
            // 有护盾时优先消耗护盾
            const shieldDamage = Math.min(this.shield, amount);
            this.shield -= shieldDamage;
            amount -= shieldDamage;
        }
        
        if (amount > 0) {
            this.health = Math.max(0, this.health - amount);
            this.lastDamageTime = Date.now(); // 记录受伤时间
            
            // 显示伤害数字
            if (window.gameEngine && typeof window.gameEngine.showFloatingText === 'function') {
                window.gameEngine.showFloatingText(this.x, this.y - 20, 
                    `-${amount}`, '#FF4444', 16);
            }
            
            // 更新UI
            this.updateHealthUI();
            
            // 受伤效果
            this.flashRed();
            
            console.log(`玩家受到伤害: ${amount}, 当前血量: ${this.health}/${this.maxHealth}`);
        }
        
        return this.health <= 0;
    }
    
    updateHealthUI() {
        const healthFill = document.getElementById('healthBarFill');
        const healthText = document.getElementById('healthText');
        
        if (healthFill && healthText) {
            const healthPercent = (this.health / this.maxHealth) * 100;
            healthFill.style.width = healthPercent + '%';
            healthText.textContent = `${this.health}/${this.maxHealth}`;
            
            // 根据血量改变颜色
            if (healthPercent > 60) {
                healthFill.style.background = 'linear-gradient(90deg, #ff6b6b, #ff8e53)';
            } else if (healthPercent > 30) {
                healthFill.style.background = 'linear-gradient(90deg, #ffa500, #ff6b6b)';
            } else {
                healthFill.style.background = 'linear-gradient(90deg, #ff0000, #8b0000)';
            }
        }
    }
    
    flashRed() {
        // 受伤闪红效果
        this.isHurt = true;
        setTimeout(() => {
            this.isHurt = false;
        }, 200);
    }
    
    pickupNearestWeapon(weapons) {
        const pickupRange = 50;
        let nearestWeapon = null;
        let nearestMeleeWeapon = null;
        let nearestDistance = pickupRange;
        
        // 检查远程武器
        weapons.forEach((weapon, index) => {
            const distance = Math.sqrt(
                Math.pow(this.x - weapon.x, 2) + Math.pow(this.y - weapon.y, 2)
            );
            
            if (distance < nearestDistance) {
                nearestDistance = distance;
                nearestWeapon = { weapon, index, type: 'ranged' };
            }
        });
        
        // 检查近战武器
        if (window.gameEngine && window.gameEngine.meleeWeapons) {
            window.gameEngine.meleeWeapons.forEach((meleeWeapon, index) => {
                if (!meleeWeapon.isDropped) return;
                
                const distance = Math.sqrt(
                    Math.pow(this.x - meleeWeapon.x, 2) + Math.pow(this.y - meleeWeapon.y, 2)
                );
                
                if (distance < nearestDistance) {
                    nearestDistance = distance;
                    nearestMeleeWeapon = { weapon: meleeWeapon, index, type: 'melee' };
                    nearestWeapon = null; // 近战武器优先
                }
            });
        }
        
        // 拾取最近的武器
        if (nearestMeleeWeapon) {
            // 拾取近战武器
            this.meleeWeapon = nearestMeleeWeapon.weapon;
            this.meleeWeapons = [this.meleeWeapon];
            window.gameEngine.meleeWeapons.splice(nearestMeleeWeapon.index, 1);
            
            // 显示拾取提示
            this.showWeaponPickupMessage(nearestMeleeWeapon.weapon.stats.name, 'melee');
            
            // 应用技能效果到新装备的近战武器
            if (typeof NewSkillTreeSystem !== 'undefined') {
                NewSkillTreeSystem.applySkillsToWeaponGlobal(this.meleeWeapon);
            }
            
            // 更新UI
            this.updateWeaponUI();
        } else if (nearestWeapon) {
            // 拾取远程武器
            this.currentWeapon = nearestWeapon.weapon;
            weapons.splice(nearestWeapon.index, 1);
            
            // 显示拾取提示
            this.showWeaponPickupMessage(nearestWeapon.weapon.weaponStats.name, 'ranged');
            
            // 应用技能效果到新装备的远程武器
            if (typeof NewSkillTreeSystem !== 'undefined') {
                NewSkillTreeSystem.applySkillsToWeaponGlobal(this.currentWeapon);
            }
            
            // 更新UI
            this.updateWeaponUI();
        }
    }
    
    // 显示武器拾取消息
    showWeaponPickupMessage(weaponName, type) {
        if (window.gameEngine) {
            window.gameEngine.floatingTexts = window.gameEngine.floatingTexts || [];
            const color = type === 'melee' ? '#FF6B6B' : '#4CAF50';
            const typeText = type === 'melee' ? '近战武器' : '远程武器';
            
            window.gameEngine.floatingTexts.push(new FloatingText(
                this.x, this.y - 60, 
                `获得${typeText}: ${weaponName}`,
                color, 
                2000
            ));
        }
    }
    
    updateWeaponUI() {
        const ammoCount = document.getElementById('ammoCount');
        if (ammoCount && this.currentWeapon) {
            ammoCount.textContent = 
                `${this.currentWeapon.currentAmmo}/${this.currentWeapon.totalAmmo}`;
        }
    }
    
    // 道具效果方法
    applySpeedBoost(multiplier, duration) {
        this.activeEffects.speed = {
            multiplier: multiplier,
            endTime: Date.now() + duration,
            originalSpeed: this.speed
        };
        this.speed *= multiplier;
        
        setTimeout(() => {
            if (this.activeEffects.speed) {
                this.speed = this.activeEffects.speed.originalSpeed;
                delete this.activeEffects.speed;
            }
        }, duration);
    }
    
    applyDamageBoost(multiplier, duration) {
        this.activeEffects.damage = {
            multiplier: multiplier,
            endTime: Date.now() + duration
        };
        
        setTimeout(() => {
            delete this.activeEffects.damage;
        }, duration);
    }
    
    applyRapidFire(multiplier, duration) {
        if (!this.currentWeapon) return;
        
        this.activeEffects.rapidFire = {
            multiplier: multiplier,
            endTime: Date.now() + duration,
            originalFireRate: this.currentWeapon.fireRate
        };
        
        this.currentWeapon.fireRate /= multiplier;
        
        setTimeout(() => {
            if (this.activeEffects.rapidFire && this.currentWeapon) {
                this.currentWeapon.fireRate = this.activeEffects.rapidFire.originalFireRate;
                delete this.activeEffects.rapidFire;
            }
        }, duration);
    }
    
    addShield(amount) {
        this.shield += amount;
    }
    
    addExplosiveAmmo(amount) {
        this.explosiveAmmo += amount;
    }
    
    render(ctx) {
        ctx.save();
        
        // 受伤效果
        if (this.isHurt) {
            ctx.globalAlpha = 0.5;
            ctx.fillStyle = '#FF0000';
            ctx.fillRect(this.x - 20, this.y - 20, 40, 40);
        }
        
        // 移动到玩家位置
        ctx.translate(this.x, this.y);
        
        // 绘制玩家身体 (像素艺术风格)
        this.drawPixelPlayer(ctx);
        
        // 绘制武器
        if (this.combatMode === 'ranged' && this.currentWeapon) {
            this.drawWeapon(ctx);
        } else if (this.combatMode === 'melee' && this.meleeWeapon) {
            this.drawMeleeWeapon(ctx);
            
            // 近战攻击时显示攻击范围
            if (this.isAttacking) {
                ctx.strokeStyle = 'rgba(255, 0, 0, 0.4)';
                ctx.lineWidth = 2;
                ctx.beginPath();
                ctx.arc(0, 0, this.meleeWeapon.range, 0, Math.PI * 2);
                ctx.stroke();
            }
        }
        
        // 绘制瞄准线
        this.drawAimLine(ctx);
        
        ctx.restore();
    }
    
    drawPixelPlayer(ctx) {
        const size = 20; // 增大角色尺寸
        const halfSize = size / 2;
        
        // 移动动画效果
        let legOffset = 0;
        if (this.isMoving) {
            legOffset = Math.sin(this.animationFrame * Math.PI / 2) * 2;
        }
        
        // 阴影
        ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
        ctx.fillRect(-halfSize + 2, halfSize + 2, size - 4, 4);
        
        // 腿部 (带走路动画)
        ctx.fillStyle = '#2E4057'; // 军裤颜色
        ctx.fillRect(-halfSize + 2, halfSize - 8, 6, 8 + legOffset);
        ctx.fillRect(-halfSize + 10, halfSize - 8, 6, 8 - legOffset);
        
        // 靴子
        ctx.fillStyle = '#1C1C1C';
        ctx.fillRect(-halfSize + 1, halfSize - 2, 8, 3);
        ctx.fillRect(-halfSize + 9, halfSize - 2, 8, 3);
        
        // 身体躯干
        ctx.fillStyle = '#4A6741'; // 军绿色制服
        ctx.fillRect(-halfSize + 1, -halfSize + 4, size - 2, 12);
        
        // 制服细节
        ctx.fillStyle = '#3A5431';
        ctx.fillRect(-halfSize + 3, -halfSize + 6, size - 6, 2); // 胸前口袋
        ctx.fillRect(-halfSize + 8, -halfSize + 9, 2, 6); // 纽扣
        
        // 手臂
        ctx.fillStyle = '#4A6741';
        if (this.currentWeapon) {
            // 持枪姿势
            ctx.fillRect(-halfSize - 2, -halfSize + 2, 4, 8); // 左手
            ctx.fillRect(halfSize - 2, -halfSize + 2, 4, 8);  // 右手
        } else {
            // 普通姿势
            ctx.fillRect(-halfSize - 1, -halfSize + 4, 3, 10);
            ctx.fillRect(halfSize - 2, -halfSize + 4, 3, 10);
        }
        
        // 头部皮肤
        ctx.fillStyle = '#FDBCB4'; // 肤色
        ctx.fillRect(-halfSize + 3, -halfSize, 14, 8);
        
        // 头发/头盔
        ctx.fillStyle = '#654321'; // 军帽/头发
        ctx.fillRect(-halfSize + 2, -halfSize - 2, 16, 4);
        
        // 面部特征
        ctx.fillStyle = '#000000';
        // 眼睛
        ctx.fillRect(-halfSize + 5, -halfSize + 2, 2, 1);
        ctx.fillRect(-halfSize + 11, -halfSize + 2, 2, 1);
        
        // 嘴巴
        ctx.fillStyle = '#8B4513';
        ctx.fillRect(-halfSize + 8, -halfSize + 5, 2, 1);
        
        // 装备细节
        ctx.fillStyle = '#2F4F4F';
        ctx.fillRect(-halfSize + 2, -halfSize + 8, 3, 2); // 左肩章
        ctx.fillRect(-halfSize + 13, -halfSize + 8, 3, 2); // 右肩章
        
        // 弹药带
        ctx.fillStyle = '#8B4513';
        ctx.fillRect(-halfSize + 1, -halfSize + 10, size - 2, 2);
        
        // 战术背心细节
        ctx.fillStyle = '#2F4F4F';
        ctx.fillRect(-halfSize + 4, -halfSize + 12, 3, 2);
        ctx.fillRect(-halfSize + 11, -halfSize + 12, 3, 2);
    }
    
    drawWeapon(ctx) {
        if (!this.currentWeapon) return;
        
        ctx.save();
        ctx.rotate(this.facing);
        
        // 根据武器类型绘制不同的武器
        switch (this.currentWeapon.type) {
            case 'pistol':
                this.drawPistol(ctx);
                break;
            case 'rifle':
                this.drawRifle(ctx);
                break;
            case 'shotgun':
                this.drawShotgun(ctx);
                break;
            case 'smg':
                this.drawSMG(ctx);
                break;
            case 'sniper':
                this.drawSniper(ctx);
                break;
            case 'minigun':
                this.drawMinigun(ctx);
                break;
            case 'laser':
                this.drawLaser(ctx);
                break;
            case 'plasma':
                this.drawPlasma(ctx);
                break;
            default:
                this.drawPistol(ctx);
        }
        
        ctx.restore();
    }
    
    drawPistol(ctx) {
        // 手枪握把
        ctx.fillStyle = '#2F2F2F';
        ctx.fillRect(8, -1, 4, 6);
        
        // 枪身
        ctx.fillStyle = '#4A4A4A';
        ctx.fillRect(12, -2, 12, 4);
        
        // 枪口
        ctx.fillStyle = '#1A1A1A';
        ctx.fillRect(24, -1, 3, 2);
        
        // 扳机护圈
        ctx.fillStyle = '#2F2F2F';
        ctx.fillRect(10, 1, 3, 2);
    }
    
    drawRifle(ctx) {
        // 枪托
        ctx.fillStyle = '#8B4513';
        ctx.fillRect(5, -1, 6, 4);
        
        // 枪身
        ctx.fillStyle = '#2F2F2F';
        ctx.fillRect(11, -2, 20, 4);
        
        // 枪管
        ctx.fillStyle = '#1A1A1A';
        ctx.fillRect(31, -1, 8, 2);
        
        // 瞄准镜
        ctx.fillStyle = '#4A4A4A';
        ctx.fillRect(18, -4, 8, 2);
    }
    
    drawShotgun(ctx) {
        // 枪托
        ctx.fillStyle = '#8B4513';
        ctx.fillRect(4, -2, 8, 6);
        
        // 枪身
        ctx.fillStyle = '#2F2F2F';
        ctx.fillRect(12, -3, 16, 6);
        
        // 粗枪管
        ctx.fillStyle = '#1A1A1A';
        ctx.fillRect(28, -2, 8, 4);
        
        // 泵动机构
        ctx.fillStyle = '#4A4A4A';
        ctx.fillRect(20, -1, 4, 2);
    }
    
    drawSMG(ctx) {
        // 枪托
        ctx.fillStyle = '#2F2F2F';
        ctx.fillRect(6, -1, 5, 4);
        
        // 枪身
        ctx.fillStyle = '#4A4A4A';
        ctx.fillRect(11, -2, 15, 4);
        
        // 枪管
        ctx.fillStyle = '#1A1A1A';
        ctx.fillRect(26, -1, 6, 2);
        
        // 弹夹
        ctx.fillStyle = '#2F2F2F';
        ctx.fillRect(15, 2, 4, 8);
    }
    
    drawSniper(ctx) {
        // 枪托
        ctx.fillStyle = '#8B4513';
        ctx.fillRect(3, -2, 8, 6);
        
        // 枪身
        ctx.fillStyle = '#2F2F2F';
        ctx.fillRect(11, -3, 25, 6);
        
        // 长枪管
        ctx.fillStyle = '#1A1A1A';
        ctx.fillRect(36, -2, 12, 4);
        
        // 瞄准镜
        ctx.fillStyle = '#4A4A4A';
        ctx.fillRect(15, -6, 15, 3);
        
        // 支架
        ctx.fillStyle = '#666666';
        ctx.fillRect(25, 3, 2, 4);
    }
    
    drawMinigun(ctx) {
        // 枪托/握把
        ctx.fillStyle = '#2F2F2F';
        ctx.fillRect(5, -2, 6, 8);
        
        // 主体
        ctx.fillStyle = '#4A4A4A';
        ctx.fillRect(11, -4, 20, 8);
        
        // 多枪管
        ctx.fillStyle = '#1A1A1A';
        ctx.fillRect(31, -3, 10, 6);
        
        // 弹药箱
        ctx.fillStyle = '#8B4513';
        ctx.fillRect(8, 4, 8, 6);
        
        // 散热片
        ctx.fillStyle = '#666666';
        ctx.fillRect(18, -2, 2, 4);
        ctx.fillRect(22, -2, 2, 4);
    }
    
    drawLaser(ctx) {
        // 枪托
        ctx.fillStyle = '#2F2F2F';
        ctx.fillRect(6, -1, 6, 4);
        
        // 枪身
        ctx.fillStyle = '#4169E1';
        ctx.fillRect(12, -2, 18, 4);
        
        // 激光发射器
        ctx.fillStyle = '#00FFFF';
        ctx.fillRect(30, -1, 6, 2);
        
        // 能量槽
        ctx.fillStyle = '#0000FF';
        ctx.fillRect(16, -1, 10, 2);
        
        // 发光效果
        ctx.fillStyle = '#FFFFFF';
        ctx.fillRect(32, -0.5, 2, 1);
    }
    
    drawPlasma(ctx) {
        // 枪托
        ctx.fillStyle = '#2F2F2F';
        ctx.fillRect(5, -2, 7, 6);
        
        // 枪身
        ctx.fillStyle = '#8A2BE2';
        ctx.fillRect(12, -3, 16, 6);
        
        // 等离子发射器
        ctx.fillStyle = '#FF00FF';
        ctx.fillRect(28, -2, 8, 4);
        
        // 能量环
        ctx.strokeStyle = '#00FF00';
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.arc(32, 0, 3, 0, Math.PI * 2);
        ctx.stroke();
        
        // 等离子效果
        ctx.fillStyle = '#FFFF00';
        ctx.fillRect(34, -1, 3, 2);
    }
    
    drawMeleeWeapon(ctx) {
        if (!this.meleeWeapon) return;
        
        ctx.save();
        ctx.rotate(this.facing);
        
        // 近战攻击时的特殊效果
        if (this.isAttacking) {
            const attackProgress = (Date.now() - this.attackStartTime) / this.attackDuration;
            const swingAngle = Math.sin(attackProgress * Math.PI) * 0.5;
            ctx.rotate(swingAngle);
        }
        
        // 使用近战武器的渲染方法
        this.meleeWeapon.render(ctx, 0, 0, 0);
        
        ctx.restore();
    }
    
    drawAimLine(ctx) {
        ctx.save();
        ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
        ctx.lineWidth = 1;
        ctx.setLineDash([5, 5]);
        
        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.lineTo(Math.cos(this.facing) * 100, Math.sin(this.facing) * 100);
        ctx.stroke();
        
        ctx.restore();
    }
    
    // 缺失的方法实现
    die() {
        console.log('玩家死亡');
        if (window.gameManager) {
            window.gameManager.gameOver();
        }
    }
    
    heal(amount) {
        this.health = Math.min(this.maxHealth, this.health + amount);
        this.updateHealthUI();
    }
    
    flashRed() {
        this.isHurt = true;
        setTimeout(() => {
            this.isHurt = false;
        }, 200);
    }
    
    updateHealthUI() {
        const healthBar = document.getElementById('healthBarFill');
        const healthText = document.getElementById('healthText');
        
        if (healthBar) {
            const healthPercent = (this.health / this.maxHealth) * 100;
            healthBar.style.width = healthPercent + '%';
            
            // 根据血量改变颜色
            if (healthPercent > 60) {
                healthBar.style.backgroundColor = '#00ff00';
            } else if (healthPercent > 30) {
                healthBar.style.backgroundColor = '#ffff00';
            } else {
                healthBar.style.backgroundColor = '#ff0000';
            }
        }
        
        if (healthText) {
            healthText.textContent = `${this.health}/${this.maxHealth}`;
        }
    }
    
    updateWeaponUI() {
        const ammoCount = document.getElementById('ammoCount');
        if (ammoCount) {
            if (this.combatMode === 'ranged' && this.currentWeapon) {
                ammoCount.textContent = `${this.currentWeapon.currentAmmo}/${this.currentWeapon.totalAmmo}`;
            } else if (this.combatMode === 'melee' && this.meleeWeapon) {
                ammoCount.textContent = `${this.meleeWeapon.stats.name} - 伤害:${this.meleeWeapon.stats.damage} 范围:${this.meleeWeapon.stats.range}`;
            }
        }
        
        // 更新模式显示
        const modeDisplay = document.getElementById('combatModeDisplay');
        if (modeDisplay) {
            modeDisplay.textContent = this.combatMode === 'ranged' ? '远程模式' : '近战模式';
        }
    }
    
    // 显示模式切换提示
    showModeSwitch() {
        if (window.gameEngine) {
            window.gameEngine.floatingTexts = window.gameEngine.floatingTexts || [];
            window.gameEngine.floatingTexts.push(new FloatingText(
                this.x, this.y - 50, 
                this.combatMode === 'ranged' ? '切换到远程模式' : '切换到近战模式',
                '#00FF00', 
                1500
            ));
        }
    }
    
    // 创建近战攻击特效
    createMeleeEffect(targetX, targetY) {
        if (!window.gameEngine) return;
        
        const angle = Math.atan2(targetY - this.y, targetX - this.x);
        const effectDistance = 40;
        const effectX = this.x + Math.cos(angle) * effectDistance;
        const effectY = this.y + Math.sin(angle) * effectDistance;
        
        // 创建攻击斩击特效
        for (let i = 0; i < 8; i++) {
            const offsetAngle = angle + (Math.random() - 0.5) * Math.PI / 3;
            const distance = Math.random() * 30 + 20;
            const particleX = effectX + Math.cos(offsetAngle) * distance;
            const particleY = effectY + Math.sin(offsetAngle) * distance;
            
            window.gameEngine.particles.push(new Particle(
                particleX,
                particleY,
                (Math.random() - 0.5) * 100,
                (Math.random() - 0.5) * 100,
                '#FFFF00',
                300 + Math.random() * 200
            ));
        }
        
        // 创建冲击波效果
        for (let i = 0; i < 5; i++) {
            const shockAngle = angle + (Math.random() - 0.5) * Math.PI / 2;
            window.gameEngine.particles.push(new Particle(
                effectX,
                effectY,
                Math.cos(shockAngle) * 80,
                Math.sin(shockAngle) * 80,
                '#FF8C00',
                200
            ));
        }
    }
    
    // 创建血液特效
    createBloodEffect(x, y) {
        // 禁用血液特效 - 不再创建红色圆圈
        return;
        /*
        if (!window.gameEngine) return;
        
        for (let i = 0; i < 12; i++) {
            const angle = Math.random() * Math.PI * 2;
            const speed = Math.random() * 60 + 20;
            const bloodColor = i % 2 === 0 ? '#FF0000' : '#8B0000';
            
            window.gameEngine.particles.push(new Particle(
                x + (Math.random() - 0.5) * 10,
                y + (Math.random() - 0.5) * 10,
                Math.cos(angle) * speed,
                Math.sin(angle) * speed,
                bloodColor,
                500 + Math.random() * 300
            ));
        }
        */
    }
    
    // 创建BOSS击中特效
    createBossHitEffect(x, y) {
        if (!window.gameEngine) return;
        
        // 创建特殊的BOSS击中特效
        for (let i = 0; i < 15; i++) {
            const angle = Math.random() * Math.PI * 2;
            const speed = Math.random() * 80 + 40;
            const colors = ['#FF0000', '#FF4500', '#FFA500', '#FFFF00'];
            const color = colors[Math.floor(Math.random() * colors.length)];
            
            window.gameEngine.particles.push(new Particle(
                x + (Math.random() - 0.5) * 20,
                y + (Math.random() - 0.5) * 20,
                Math.cos(angle) * speed,
                Math.sin(angle) * speed,
                color,
                800 + Math.random() * 400
            ));
        }
        
        // 创建震荡效果
        for (let i = 0; i < 8; i++) {
            const shockAngle = (Math.PI * 2 / 8) * i;
            window.gameEngine.particles.push(new Particle(
                x + Math.cos(shockAngle) * 30,
                y + Math.sin(shockAngle) * 30,
                Math.cos(shockAngle) * 120,
                Math.sin(shockAngle) * 120,
                '#FFFFFF',
                400
            ));
        }
    }
}